<?php
class Upload{

private $size;//允许上传的文件大小
private $type;//允许上传的文件类型
private $path;//上传的文件存储路径
private $name;
public $error;

public function __construct($path=NULL,$size=NULL,$type=NULL){
	 $this->size = is_null($size)?C('FILE_SIZE'):$size;
	 $this->type = is_null($type)?C('FILE_TYPE'):$size;
	 $this->path = is_null($path)?C('FILE_URL'):$path;
}

public function up(){
	// 重组数组
	$arr = $this->reset_arr();
	//判定是否符合要求 就是筛选
	$this->filter($arr);
	is_null($this->error) && $this->move($arr);
	//如果符合要求咱门就上传文件
	return(is_null($this->error));
}

private function reset_arr(){
	//重组数组
	$arr = array();
	foreach ($_FILES as $v) {
		if(is_array($v['name'])){
			foreach ($v['name'] as $key => $value) {
				$arr[] = array(
					'name' 		=> $value,
					'tmp_name'	=> $v['tmp_name'][$key],
					'error'		=> $v['error'][$key],
					'type'		=> $v['type'][$key],
					'size'		=> $v['size'][$key],
				);
			}
		}else{
			$arr[] = $v;
		}
	}
	return $arr;
}

private function filter($arr){
	//判定是否符合要求 就是筛选
	foreach ($arr as $v) {
		//大小是否符合要求
		if($v['size'] > $this->size){
			$this->error[] = $v['name']."文件大小超过要求";
		}
		//类型是否符合要求
		$typeName = ltrim(strrchr($v['name'], '.'),'.');
		if(!in_array($typeName, $this->type)){
			$this->error[] = $v['name']."文件类型不符合要求";
		}
		//是否是合法上传文件
		if(!is_uploaded_file($v['tmp_name'])){
			$this->error[] = $v['name']."不是一个合法上传文件";
		}
		//4种错误判断
		switch (true) {
			case $v['error'] == 1:
				$this->error[] = $v['name'].'大小超过了 php.ini 中 upload_max_filesize 限制值';
				break;
			case $v['error'] == 2:
				$this->error[] = $v['name'].'大小超过HTML 表单中MAX_FILE_SIZE 选项指定的值';
				break;
			case $v['error'] == 3:
				$this->error[] = $v['name'].'文件只有部分被上传。';
				break;
			case $v['error'] == 4:
				$this->error[] = $v['name'].'没有文件被上传';
				break;
		}
		

	}
}

private function move($arr){
	//上传文件
	foreach ($arr as $v) {
		$path = rtrim(str_replace("\\", "/", $this->path),'/');
		is_dir($path) || mkdir($path,0777,true);
		$typeName = ltrim(strrchr($v['name'], '.'),'.');
		$dest = $path."/".time().mt_rand(0,99999).'.'.$typeName;
		$this->name = $dest;
		move_uploaded_file($v['tmp_name'], $dest);
	}
}
public function getName(){
	return $this->name;
}







}

?>